/*
 * @Description:过滤
 * @Version: 2.0
 * @Autor: wiz
 * @Date: 2022-12-16 19:55:09
 * @LastEditors: swc
 * @LastEditTime: 2024-06-14 17:05:03
 */
import { ifs, ts, Tsrv, tvs, vxeConfig } from '../config';
import { T_bgdSort } from './sort';

export class T_bgdFilter extends T_bgdSort {
  public Tfilter: ts.T_filter;

  // 初始化的过滤条件 （适用于：ifs.I_fv）
  protected initFilter: ifs.I_fv[] = [];

  // 字段选择过滤map[字段名]选择的值[]   （注：字段筛选条件用）
  protected selectFilter: Map<string, Set<string | number | null>>;

  // 外部注入（例如：事件注入、、、）
  protected injectFilter: ts.T_filter = new ts.T_filter();

  constructor(obj: any) {
    super(obj);
    this.Tfilter = new ts.T_filter();
    this.selectFilter = new Map();
  }

  // 将ininFilte 和 filter 合并并生成过滤条件,它们是and关系
  public getFilter(): object {
    let filter: object;
    const initFilter = this.Tfilter.parseFvs(this.initFilter);
    const selectFilter = this.Tfilter.parseSelectFilter(this.selectFilter);
    const initFilterIsNull = Object.keys(initFilter).length === 0;
    const selectFilterIsNull = Object.keys(selectFilter).length === 0;
    const injectFilterIsNull =
      Object.keys(this.injectFilter.filter).length === 0;

    // if (!initFilterIsNull && !selectFilterIsNull) {
    //   filter = this.Tfilter.parseAND([initFilter, selectFilter]);
    // } else if (!initFilterIsNull) {
    //   filter = initFilter;
    // } else if (!selectFilterIsNull) {
    //   filter = selectFilter;
    // } else {
    //   filter = {};
    // }

    const fliters: object[] = [];
    if (!initFilterIsNull) {
      fliters.push(initFilter);
    }
    if (!selectFilterIsNull) {
      fliters.push(selectFilter);
    }
    if (!injectFilterIsNull) {
      fliters.push(this.injectFilter.filter);
    }
    if (fliters.length > 0) {
      filter = this.Tfilter.parseAND(fliters);
    } else {
      filter = {};
    }

    if (
      Tsrv.utils.noValue(filter) &&
      !Tsrv.utils.noValue(this.Tfilter.filter)
    ) {
      return this.Tfilter.filter;
    }
    if (!Tsrv.utils.noValue(this.Tfilter.filter)) {
      // // this.Tfilter.mergeFilter({ obj: filter, s: tvs.V_filterLogical.NOR });
      // this.Tfilter.mergeFilter({ obj: filter, s: tvs.V_filterLogical.AND });
      // return this.Tfilter.filter;
      return this.Tfilter.parseAND([this.Tfilter.filter, filter]);
    }
    return filter;
  }

  /**
   * @description 情况一：当 p 类型为ifs.I_filter时，该过滤条件写入到this.Tfilter.filter中
   * @description 情况二：当 p 类型为非ifs.I_filter时，该过滤条件写入到 initFilter 中
   * @description 最终过滤条件 分四块结合 1、this.Tfilter.filter直接赋值， 2、initFilter（），3、selectFilter（字段筛选所用），4、this.injectFilter
   *  addInitFilter 添加初始过滤
   */
  public addInitFilter(
    p:
      | string
      | ifs.I_filter
      | { field: string; value: string | number | null }
      | { field: string; value: string | number | null }[],
    value: string | number | null = null // a|b
  ) {
    if (p instanceof ts.T_filter) {
      this.Tfilter.filter = p.filter;
    } else {
      vxeConfig.pushFieldValueDict(this.initFilter, p, value);
    }
  }

  /**
   * removeInitFilter 移除初始过滤
   */
  public removeInitFilter(field: string | string[]) {
    vxeConfig.removeFieldValueDict(this.initFilter, field);
  }

  /**
   *清除过滤条件
   */
  public clearFilter() {
    this.initFilter = [];
    this.injectFilter = new ts.T_filter();
    this.globalSearchText = '';
    this.setGlobalSearchText('');
    this.selectFilter = new Map();
    this.Tfilter.clearFilter();
    this.grid.clearFilter();
    // 清除栏位过滤选择list
    const columns = this.grid.getColumns();
    if (Array.isArray(columns)) {
      for (const idx in columns) {
        if (columns[idx]?.params?.filters) {
          for (const index in columns[idx].params.filters) {
            if (columns[idx].params.filters[index].isChk) {
              columns[idx].params.filters[index].isChk = false;
            }
          }
        }
      }
    }
  }

  /**
   * 单列筛选
   */
  public addFilter(
    field: string,
    value: string | number | null = null,
    updateFilter = true
  ) {
    if (value) {
      // const find = Tsrv.utils.find(this.m2oList, el => el.field === field);
      // if (find) {
      //   field = find.m2oField;
      // }
      if (this.selectFilter.has(field)) {
        if (Array.isArray(value) && value.length === 0) {
          this.selectFilter.delete(field);
        } else {
          this.selectFilter.get(field).add(value);
        }
      } else {
        if (Array.isArray(value) && value.length === 0) {
          return;
        }
        const setV: Set<string | number | null> = new Set();
        setV.add(value);
        this.selectFilter.set(field, setV);
      }
    }
  }

  /**
   * 设置外部注入的过滤条件
   */
  public setInjectFilter(p: ifs.I_filter | ifs.I_fv[] | object) {
    if (Tsrv.noValue(p)) {
      return;
    }
    if (p instanceof ts.T_filter) {
      this.injectFilter.filter = p.filter;
    }
    if (Object.prototype.toString.call(p) === '[object Object]') {
      const props = Object.keys(p);
      // const props = Object.getOwnPropertyNames(p);
      if (
        props.length === 2 &&
        props.includes('field') &&
        props.includes('value')
      ) {
        p = [p] as ifs.I_fv[];
      }
    }
    if (Tsrv.utils.isArray(p)) {
      p = Tsrv.utils.clone(p, true) as ifs.I_fv[];
      p = [...new Set(p as ifs.I_fv[])];
      this.injectFilter.filter = this.Tfilter.parseFvs(p as ifs.I_fv[]);
    }
  }

  /**
   * 筛选方法
   */
  public filterChange(e: any) {
    const property = e?.property ?? '';
    // const isResetFilter: boolean = e.filters.length === 0;
    const isResetFilter: boolean = !e.filters.find(
      f => f.property === property
    );
    // const filters = e.column.params.filters;
    const filters = e.column.params.filtersSelected;
    const filterMap: Map<string, Set<string | number | null>> = new Map();
    for (const idx in filters) {
      const filterField: string = filters[idx].filterField;
      const isChk: boolean = filters[idx].isChk;
      let filterValue: any = filters[idx].filterValue;
      // 过滤重置
      if (isResetFilter) {
        if (isChk) {
          filters[idx].isChk = false;
        }
        if (this.selectFilter.get(filterField)) {
          // 对所选内容进行重置
          this.selectFilter.delete(filterField);
          // 以下在修改 字段过滤 机制后 不适用 ———— 注释
          // 将this.Tfilter.filter中的过滤条件也清除掉
          // if (this.Tfilter.filter['$and']) {
          //   this.Tfilter.filter['$and'].forEach((item, index) => {
          //     if (item[filterField]) {
          //       this.Tfilter.filter['$and'].splice(index, 1);
          //     }
          //   });
          //   if (this.Tfilter.filter['$and'].length <= 1) {
          //     this.Tfilter.filter = this.Tfilter.filter['$and'][0];
          //   }
          // }
        }
      } else {
        if (isChk) {
          // 当下拉字段做筛选时，vxe-table会将0转换成null
          if (
            !Tsrv.utils.noValue(
              this.oBaseGrid.GT_editor.slcList.find(
                el => el.field === filterField
              )
            ) &&
            filterValue === null
          ) {
            filterValue = 0;
          }
          if (!Tsrv.utils.noValue(filterValue)) {
            if (filterMap.has(filterField)) {
              filterMap.get(filterField).add(filterValue);
            } else {
              const setV: Set<string | number | null> = new Set();
              setV.add(filterValue);
              filterMap.set(filterField, setV);
            }
          }
        }
      }
    }
    if (isResetFilter) {
      // 重置该属性的 部分参数
      Tsrv.utils.clear(e.column.params.filtersSelected);
      e.column.params.filterListParams.currentPage = 1;
      e.column.params.filterListParams.pageSize = 30;
      e.column.params.filterListParams.total = 0;
      e.column.params.filterListParams.searchKey = '';
    }
    if (!Tsrv.utils.noValue(filterMap)) {
      filterMap.forEach((key, value) => {
        this.selectFilter.set(value, key);
      });
    }
  }

  private replaceSensitive(value) {
    if (typeof value === 'string') {
      return (
        value
          .replace(/,/g, '\\,')
          .replace(/:/g, '\\:')
          // .replace(/\|/g, "\\|")
          .replace(/\*/g, '\\*')
      );
    }
    return value;
  }

  /**
   * 根据sort.obj设置icon的激活状态
   */
  public setSortAndFilterActive() {
    // Set Sort
    const ele = this.grid.$vnode.elm?.parentNode as HTMLElement;
    const rows = ele.querySelectorAll('.vxe-header--row');

    const sort = Tsrv.utils.clone(this.sort, true);
    // const filter = Tsrv.utils.clone(this.filterObj, true);

    const columnsObj = this.grid.getTableColumn();
    if (columnsObj) {
      const columns = columnsObj.visibleColumn;
      columns.forEach((el, index) => {
        const columnNode = this.getColumnHeaderNode(rows, el.id);
        if (columnNode) {
          // if (sort[el.field] || filter[el.field]) {
          if (sort[el.field] || this.selectFilter.has(el.field)) {
            if (sort[el.field]) {
              const order = sort[el.field].value;
              const sortAscIcon = columnNode.querySelector(
                '.vxe-sort--asc-btn'
              );
              const sortDescIcon = columnNode.querySelector(
                '.vxe-sort--desc-btn'
              );
              if (order === 'asc') {
                sortAscIcon?.classList.add('sort-filter-active');
                sortDescIcon?.classList.remove(
                  'sort-filter-active',
                  'sort--active'
                );
                columnNode.classList.add('sort--actived');
              } else if (order === 'desc') {
                sortAscIcon?.classList.remove(
                  'sort-filter-active',
                  'sort--active'
                );
                sortDescIcon?.classList.add('sort-filter-active');
                columnNode.classList.add('sort--actived');
              } else {
                sortAscIcon?.classList.remove(
                  'sort-filter-active',
                  'sort--active'
                );
                sortDescIcon?.classList.remove(
                  'sort-filter-active',
                  'sort--active'
                );
                columnNode.classList.remove('sort--actived');
              }
            }
            // if (filter[el.field]) {
            if (this.selectFilter.has(el.field)) {
              columnNode.classList.add('filter--active');
            } else {
              columnNode.classList.remove('filter--active');
            }
          } else {
            columnNode.classList.remove('filter--active');
            columnNode.classList.remove('sort--actived');
          }
        }
      });
    }
  }

  /**
   * 获取表头节点
   */
  private getColumnHeaderNode(
    rows: NodeListOf<Element>,
    columnID: string
  ): Element | null {
    for (let s = 0; s < rows.length; s++) {
      for (let i = 0; i < rows[s].childElementCount; i++) {
        if (rows[s].children[i].getAttribute('data-colid') === columnID) {
          return rows[s].children[i];
        }
      }
    }
    return null;
  }
}
export interface I_bgdFilter extends T_bgdFilter {}
